package com.chaoxin.lovehelp.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaoxin.lovehelp.common.enums.ErrorCode;
import com.chaoxin.lovehelp.common.enums.SystemEnum;
import com.chaoxin.lovehelp.common.exception.BusinessException;
import com.chaoxin.lovehelp.common.utils.OSSClientUtil;
import com.chaoxin.lovehelp.dao.*;
import com.chaoxin.lovehelp.entity.*;
import com.chaoxin.lovehelp.common.enums.vo.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaoxin.lovehelp.common.utils.PageUtils;

import com.chaoxin.lovehelp.service.ActivityRecordService;

import javax.servlet.http.HttpServletRequest;

import static java.lang.String.format;


@Service("activityRecordService")
public class ActivityRecordServiceImpl extends ServiceImpl<ActivityRecordDao, ActivityRecordEntity> implements ActivityRecordService {

    @Autowired
    private ActivityDao activityDao;
    @Autowired
    private FellowDao fellowDao;
    @Autowired
    private RecipientDao recipientDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private ActivityRecordDao activityRecordDao;


    public List<allActivityRecordVo> getAllActivityRecordVoList(Map<String, Object> params) throws ParseException {
        QueryWrapper<ActivityRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("is_display",1);
        //筛选条件
        String activityName = (String)params.get("activityName");
        String recipientName = (String)params.get("recipientName");
        String startTime = (String)params.get("startTime");
        String endTime = (String)params.get("endTime");
        String categoryId = (String)params.get("categoryId");
        String startAge = (String)params.get("startAge");
        String endAge = (String)params.get("endAge");
        String nurseGrade = (String)params.get("nurseGrade");
        String address = (String) params.get("address");
        SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<ActivityRecordEntity> activityRecords = this.list(wrapper);
        List<allActivityRecordVo> vos = new ArrayList<>();

        for (int i = 0;i<activityRecords.size();i++ ){
            allActivityRecordVo vo = new allActivityRecordVo();
            ActivityRecordEntity activityRecord = activityRecords.get(i);
            BeanUtils.copyProperties(activityRecord,vo);
            ActivityEntity activity = activityDao.selectById(vo.getActivityId());
            String actName = activity.getName();

            if(!StringUtils.isEmpty(activityName)){
                //根据活动名称筛选
                if(actName.indexOf(activityName)<0){
                    continue;
                }
            }
            if(!StringUtils.isEmpty(startTime)){
                //根据开始时间筛选
                Date startDate = sdf.parse(startTime);
                if (activity.getStartTime().before(startDate)){
                    continue;
                }

            }
            if(!StringUtils.isEmpty(endTime)){
                //根据结束时间筛选
                Date endDate = sdf.parse(endTime);
                if(activity.getStartTime().after(endDate)){
                    continue;
                }
            }
            vo.setStartTime(activity.getStartTime());
            vo.setActivityName(actName);
            FellowEntity fellow = fellowDao.selectById(activity.getResFellowId());
            vo.setFellowName(fellow.getName());
            vo.setFellowTel(fellow.getTel());
            RecipientEntity recipient = recipientDao.selectById(vo.getRecipientId());
            String recName = recipient.getName();

            //根据受助者名称筛选
            if(!StringUtils.isEmpty(recipientName)){
                if(recName.indexOf(recipientName)<0){
                    continue;
                }
            }
            //根据受助者类别筛选
            if(!StringUtils.isEmpty(categoryId)){
                if(recipient.getCategoryId()!=Integer.parseInt(categoryId)){
                    continue;
                }
            }
            //根据开始年龄筛选
            if(!StringUtils.isEmpty(startAge)){
                if (recipient.getAge()==null||recipient.getAge()<Integer.parseInt(startAge)){
                    continue;
                }
            }
            //根据结束年龄筛选
            if(!StringUtils.isEmpty(endAge)){
                if (recipient.getAge()==null||recipient.getAge()>Integer.parseInt(endAge)){
                    continue;
                }
            }
            //根据护理等级筛选
            if(!StringUtils.isEmpty(nurseGrade)){
                if(recipient.getNurseGrade()!=Integer.parseInt(nurseGrade)){
                    continue;
                }
            }
            //根据住址筛选
            if(!StringUtils.isEmpty(address)){
                if(recipient.getAddress().indexOf(address)<0){
                    continue;
                }
            }
            vo.setRecipientName(recipient.getName());
            vo.setAddress(recipient.getAddress());
            vo.setAge(recipient.getAge());
            vo.setCategoryId(recipient.getCategoryId());
            vo.setGender(recipient.getGender());
            vo.setNurseGrade(recipient.getNurseGrade());
            //获取类别名称
            CategoryEntity category = categoryDao.selectById(recipient.getCategoryId());
            vo.setCategoryName(category.getName());
            Integer jointerId = recipient.getFellowId();
            if (jointerId!=null){//将对接者信息写入
                vo.setJointerId(jointerId);
                vo.setJointerName(fellowDao.selectById(jointerId).getName());
            }
            vos.add(vo);
        }
        return vos;
    }
    @Override
    public PageUtils queryPage(HttpServletRequest request, Map<String, Object> params) throws ParseException {
        List<allActivityRecordVo> vos = new ArrayList<>();
        vos = getAllActivityRecordVoList(params);
        //获取登录的用户
        FellowEntity loginUser =(FellowEntity) request.getSession().getAttribute(SystemEnum.LOGIN_STATUS.getName());
        //登录用户不为空
        if(loginUser==null){
            throw  new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"用户未登录");
        }
        //判断登录用户是否为管理员
        if(loginUser.getRole()!=1 && loginUser.getRole()!=2){
            //不是管理员，只能查看自己的志愿活动记录，使用迭代器剔除掉非登录用户的记录
            Iterator<allActivityRecordVo> iterator = vos.iterator();
            while (iterator.hasNext()){
                allActivityRecordVo vo = iterator.next();
                if(vo.getJointerId()!=loginUser.getId()){
                    iterator.remove();
                }
        }}

        //分页处理
        Integer pageIndex = Integer.parseInt(params.get("page").toString());
        Integer limit = Integer.parseInt(params.get("limit").toString());
        int from = (pageIndex - 1) * limit;
        int to = from + limit > vos.size() ? vos.size() : from + limit;
        List<allActivityRecordVo> vos1 = new ArrayList<>(vos.subList(from, to));
        IPage<allActivityRecordVo> page = new Page<>(pageIndex, limit);
        page.setRecords(vos1);
        page.setTotal(vos.size());
        page.setPages(vos.size() % limit > 0 ? vos.size() / limit + 1 : vos.size() / limit);
        return new PageUtils(page);
    }

    @Override
    public void removeIds(List<Integer> list) {
        if(list!=null){
            for (Integer id: list) {
                ActivityRecordEntity record = this.baseMapper.selectById(id);
                //逻辑删除
                record.setIsDisplay(0);
                this.baseMapper.updateById(record);
            }
        }
    }

    //获取某活动的受助者信息加活动记录id
    @Override
    public List<recordRecipientVo> getRecients(Integer id) {
        QueryWrapper<ActivityRecordEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("is_display",1).eq("activity_id",id);
        if(wrapper!=null){

            List<ActivityRecordEntity> list = this.list(wrapper);
            List<recordRecipientVo> vos = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                recordRecipientVo vo = new recordRecipientVo();
                vo.setId(list.get(i).getId());
                vo.setRecipientId(list.get(i).getRecipientId());
                vos.add(vo);
            }
            return vos;
        }

        return new ArrayList<>();
    }

    @Override
    public void exportRecord(Map<String, Object> params) throws ParseException {
        List<allActivityRecordVo> vos = getAllActivityRecordVoList(params);
        String fileName = (String) params.get("fileName");

        String filePath = System.getProperty("user.home")+ File.separator+"Desktop";

        fileName = filePath+"\\"+fileName+".xlsx";
        SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Workbook workbook = new XSSFWorkbook(); // 创建新的Excel工作簿
        Sheet sheet = workbook.createSheet("受助记录"); // 创建新的工作表

        //设置列宽
        sheet.setColumnWidth(0,5000);
        // 创建表头
        Row headerRow = sheet.createRow(0);
        Cell headerCell = headerRow.createCell(0);
        headerCell.setCellValue("活动名称");
        headerCell = headerRow.createCell(1);
        headerCell.setCellValue("活动时间");
        headerCell = headerRow.createCell(2);
        headerCell.setCellValue("活动负责人");
        headerCell = headerRow.createCell(3);
        headerCell.setCellValue("活动负责人电话");
        headerCell = headerRow.createCell(4);
        headerCell.setCellValue("受助者姓名");
        headerCell = headerRow.createCell(5);
        headerCell.setCellValue("性别");
        headerCell = headerRow.createCell(6);
        headerCell.setCellValue("类别");
        headerCell = headerRow.createCell(7);
        headerCell.setCellValue("护理类别");
        headerCell = headerRow.createCell(8);
        headerCell.setCellValue("居住地址");
        headerCell = headerRow.createCell(9);
        headerCell.setCellValue("年龄");
        headerCell = headerRow.createCell(10);
        headerCell.setCellValue("物资及帮助描述");

        // 遍历List<Member>并将数据写入工作表
        int rowNum = 1;
        for (allActivityRecordVo vo : vos) {
            Row dataRow = sheet.createRow(rowNum++);
            Cell dataCell = dataRow.createCell(0);
            dataCell.setCellValue(vo.getActivityName());
            dataCell = dataRow.createCell(1);
            String date = sdf.format(vo.getStartTime());
            dataCell.setCellValue(date);
            dataCell = dataRow.createCell(2);
            dataCell.setCellValue(vo.getFellowName());
            dataCell = dataRow.createCell(3);
            dataCell.setCellValue(vo.getFellowTel());
            dataCell = dataRow.createCell(4);
            dataCell.setCellValue(vo.getRecipientName());
            dataCell = dataRow.createCell(5);
            String sex = new String();
            if(vo.getGender()!=null){
                sex = vo.getGender()==0?"男":"女";
            }
            dataCell.setCellValue(sex);
            dataCell = dataRow.createCell(6);
            dataCell.setCellValue(vo.getCategoryName());
            dataCell = dataRow.createCell(7);
            String nurseName = new String();
            switch (vo.getNurseGrade()){
                case 0: nurseName = "全自理";break;

                case 1:nurseName = "半失能";break;
                case 2:nurseName = "失能";break;
                default:nurseName = "正常";break;
            }
            dataCell.setCellValue(nurseName);
            dataCell = dataRow.createCell(8);
            dataCell.setCellValue(vo.getAddress());
            dataCell = dataRow.createCell(9);
            String age = new String();
            if(vo.getAge()!=null){
                age = vo.getAge().toString();
            }
            dataCell.setCellValue(age);
            dataCell = dataRow.createCell(10);
            dataCell.setCellValue(vo.getDetail());
        }

        //设置列宽
        sheet.setColumnWidth(0,6000);
        sheet.setColumnWidth(1,5000);
        sheet.setColumnWidth(2,2700);
        sheet.setColumnWidth(3,4000);
        sheet.setColumnWidth(4,2700);
        sheet.setColumnWidth(5,1500);
        sheet.setColumnWidth(6,4000);
        sheet.setColumnWidth(7,3000);
        sheet.setColumnWidth(8,2500);
        sheet.setColumnWidth(9,1500);
        sheet.setColumnWidth(10,10000);
        // 创建文件输出流以写入文件
        try (FileOutputStream outputStream = new FileOutputStream(fileName)) {
            workbook.write(outputStream);
            System.out.println("Excel文件已生成：" + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭工作簿
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //获取某个活动记录的受助者id
    @Override
    public Integer[] getRecientIds(Integer id) {
        QueryWrapper<ActivityRecordEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("is_display",1).eq("activity_id",id).select("recipient_id");
        if(wrapper!=null){

            List<ActivityRecordEntity> list = this.list(wrapper);
            Integer[] recipientIds = new Integer[list.size()];
            for (int i = 0; i < list.size(); i++) {
                recipientIds[i] = list.get(i).getRecipientId();
            }
            return recipientIds;
        }
        return new Integer[0];
    }

    @Override
    public void removeByActivityId(Integer id) {
        QueryWrapper<ActivityRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("activity_id",id);

        this.remove(wrapper);

    }

    //获取活动记录信息
    @Override
    public recipientRecordVo getVoById(Integer id) {
        ActivityRecordEntity activityRecord = this.getById(id);
        recipientRecordVo vo = new recipientRecordVo();
        vo.setActivityRecordId(id);
        vo.setDetail(activityRecord.getDetail());
        vo.setDetailPic(activityRecord.getDetailPic()==null?"":activityRecord.getDetailPic());
        RecipientEntity recipient = recipientDao.selectById(activityRecord.getRecipientId());
        BeanUtils.copyProperties(recipient,vo);
        CategoryEntity category = categoryDao.selectById(recipient.getCategoryId());
        vo.setCategoryName(category.getName());
        if(recipient.getFellowId()!=null){
            FellowEntity fellow = fellowDao.selectById(recipient.getFellowId());
            vo.setFellowName(fellow.getName());
            vo.setFellowTel(fellow.getTel());
        }

        return vo;
    }
    /**
     *
     */

    @Scheduled(cron = "0 0 22 * * ?")
    public void deleteAliyunPicTask() {
        List<String> dataBaseFileName = this.getDataBaseFileName();
        System.out.println("数据库"+dataBaseFileName);
        OSSClientUtil ossClientUtil = new OSSClientUtil();
        //获取目录下阿里云oss的文件列表
        List<String> aliyunFileName = ossClientUtil.getFileNamesInDirectory("chaoxin");
        System.out.println("阿里云"+aliyunFileName);
        //删除列表
        List<String> deleteList = new ArrayList<>();
        for (String fileName : aliyunFileName) {
            if (!dataBaseFileName.contains(fileName)) {
                deleteList.add(fileName);
            }
        }
        System.out.println("删除列表"+deleteList);
        for (String fileName : deleteList) {
            ossClientUtil.deleteFileFromOSS(fileName);
        }
    }

    /**
     * 获取数据库的文件名
     * @return 文件名数组
     */
    public List<String> getDataBaseFileName() {
        QueryWrapper<ActivityRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("is_display", 1);
        List<String> DataBasePicList = new ArrayList<>();
        if (wrapper != null) {
            // 查询所有记录
            List<ActivityRecordEntity> list = activityRecordDao.selectList(wrapper);
            for (ActivityRecordEntity activityRecord : list) {
                System.out.println("Activity record ID: " + activityRecord);
                if (!StringUtils.isEmpty(activityRecord.getDetailPic())) {
                    String detailPicUrl = activityRecord.getDetailPic();
                    System.out.println("文件url"+activityRecord.getDetailPic());
                    List<String> detailPicList = Arrays.asList(detailPicUrl.split(","));
                    System.out.println(format("Activity record ID: {}, Detail pic list: {}", activityRecord.getId(), detailPicList));
                    for (String detailPicNameurl : detailPicList) {
                        int lastSlashIndex = detailPicNameurl.lastIndexOf('/');
                        if (lastSlashIndex != -1 && lastSlashIndex < detailPicNameurl.length() - 1) {
                            String FileName= detailPicNameurl.substring(lastSlashIndex + 1);
                            System.out.println(FileName);
//                            添加到数据数组
                            DataBasePicList.add(FileName);
                        }
                    }
                }
            }
        }
        return DataBasePicList;
    }


//    public  void deleteAliyunPicTask() {
//        QueryWrapper<ActivityRecordEntity> wrapper = new QueryWrapper<>();
////        QueryWrapper<ActivityRecordEntity> wrapper = new QueryWrapper<>();
//        wrapper.eq("is_display", 1);
//        if (wrapper != null) {
//            //查询所以所有记录
//
//            List<ActivityRecordEntity> list = ActivityRecordDao.selectList(wrapper);
//            for (int i = 0; i < list.size(); i++) {
//                ActivityRecordEntity activityRecord = list.get(i);
//                if (!StringUtils.isEmpty(activityRecord.getDetailPic())) {
//                    List<String> detailPicList = Arrays.asList(activityRecord.getDetailPic().split(","));
//                    System.out.println(detailPicList);
//                    for (int j = 0; j < detailPicList.size(); j++) {
//                        String detailPicNameurl = detailPicList.get(j);
//                        String picName = detailPicNameurl.split("/")[-1];
//                        System.out.println(picName);
//                    }
//                }
//
//            }
//        }
//        //数据库的文件名称
//
//    }

}